package org.example;

import bean.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import bean.DB;

@WebServlet("/deleteUserServlet")
public class deleteUserServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id"); // 获取传递的用户 ID

        DB db = new DB();
        String sql = "DELETE FROM users WHERE id = ?"; // SQL 删除语句

        try (Connection conn = db.createConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, Integer.parseInt(id)); // 设置 ID 参数
            int rows = pstmt.executeUpdate(); // 执行删除

            if (rows > 0) {
                ResponseUtils.sendResponse(response, "用户删除成功", "showUser.jsp");
            } else {
                ResponseUtils.sendResponse(response, "用户不存在", "showUser.jsp");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "删除失败", "showUser.jsp");
        } finally {
            db.close();
        }
    }
}
